//
//  main.c
//  C_10进程与系统调用
//
//  Created by Robin on 16/3/20.
//  Copyright © 2016年 cnbm. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
//#include <sys/wait.h>
#include <string.h>

int score = 0;

void error (char* msg){
    fprintf(stderr, "%s : %s\n",strerror(errno),msg);
}

void end_game (int sig){
    printf("\nFinal score : %i\n",score);
    exit(0);
}

int catch_sigal (int sig,void(*handle)(int)){
    
    struct sigaction action;
    
    action.sa_handler = handle;
    action.sa_flags = 0;
    sigemptyset(&action.sa_mask);
    
    return sigaction(sig, &action, NULL);
}

void time_up (int sig){
    puts("\n Times up \n");
    raise(SIGINT);
}



int main(int argc, char * argv[]) {
    
    catch_sigal(SIGALRM, time_up);
    catch_sigal(SIGINT, end_game);
    
    //srandom(time(0));
    //srandom(0);
    srandom(time(0));
    
    while (1) {
        int a = random() % 11;
        int b = random() % 11;
        char text[4];
        
        printf("\nwhat's %i times %i?\n",a,b);
        
        fgets(text, 4, stdin);
        
        //raise(SIGALRM);
        alarm(5);
        
        int answer = atoi(text);
        
        if (answer == a * b) {
            score ++;
        }else
            printf("\n Wrong , Scroe : %i\n",score);
        
    }
    
    // 可以把定为几分之一秒后响铃 但很复杂需要setitimer() 函数 http://tinyurl.com/3o7hzbm
//    char name[30];
//    puts("Please input your name:");
//    fgets(name, 30, stdin);
//    printf("Hello %s\n",name);
    
    return 0;
}
